<template>
  <div class="app-container">
    <el-card class="box-card" shadow="always" v-show="showSearch">
      <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="98px" @submit.native.prevent>
        <el-form-item label="公司名称" prop="companyName">
          <el-input v-model="queryParams.companyName" placeholder="请输入公司名称" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <!-- <el-form-item label="状态:" prop="clueStatus">
          <el-select v-model="queryParams.clueStatus" clearable reserve-keyword placeholder="状态">
            <el-option label="已领用" :value="1" />
            <el-option label="未领用" :value="0" />
          </el-select>
        </el-form-item> -->
        <el-form-item label="领用人:" prop="personAssigner">
          <el-select v-model="queryParams.personAssigner" clearable reserve-keyword placeholder="领用人">
            <el-option v-for="item in userList" :key="item.userId" :label="item.realityName" :value="item.userId" />
          </el-select>
        </el-form-item>
        <el-form-item label="报备人:" prop="createBy">
          <el-select v-model="queryParams.createBy" clearable reserve-keyword placeholder="报备人">
            <el-option v-for="item in userList" :key="item.userId" :label="item.realityName" :value="item.userId" />
          </el-select>
        </el-form-item>
        <el-form-item label="归属部门:" prop="createDept">
          <el-select v-model="queryParams.createDept" clearable reserve-keyword placeholder="归属部门">
            <el-option v-for="item in deptList" :key="item.deptId" :label="item.deptName" :value="item.deptId" />
          </el-select>
        </el-form-item>
        <el-form-item label="所属区域:">
          <el-cascader :options="options" v-model="selectedOptions"> </el-cascader>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker
            v-model="dateRange"
            style="width: 100%"
            value-format="YYYY-MM-DD"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            @change="handleQuery"
            placeholder="选择下单时间"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">搜索</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <div class="mt20 content">
      <div v-show="tableHeight && showTree" :style="`height: ${tableHeight}px;position: relative;border-radius:12px`">
        <div class="left" :style="`height: ${tableHeight}px;`">
          <div class="left-top">
            <div class="">跟单类型</div>
            <div class="">
              <img style="width: 30px; height: 30px" @click="handleEdge" :src="showTree ? imgs[1] : imgs[0]" />
            </div>
          </div>
          <el-tree
            ref="classifyTreeRef"
            class="mt-2"
            node-key="id"
            :data="followTypeList"
            :props="{ label: 'typeName', children: 'children' }"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            highlight-current
            default-expand-all
            @node-click="itemClick"
          />
          <div class="buttons">
            <div class="button" @click="handleAddClassify">
              <el-icon>
                <CirclePlus />
              </el-icon>
              <div>新增分类</div>
            </div>
            <div class="button" @click="handleEditClassify">
              <el-icon>
                <Edit />
              </el-icon>
              <div>编辑分类</div>
            </div>
            <div class="button" @click="handleDelClassify">
              <el-icon>
                <Delete />
              </el-icon>
              <div>删除分类</div>
            </div>
          </div>
        </div>
      </div>
      <el-card shadow="always" ref="table" :body-style="{ padding: '20px' }" :class="{ 'w-tree': showTree, 'w-all': !showTree }">
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" @click="handleAdd(currentItem)">添加跟单</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" :disabled="!selectedRows.length" @click="handleBatchDelete">删除 </el-button>
          </el-col>
          <right-toolbar :v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
        <el-table
          :height="'calc(100vh - 422px)'"
          size="large"
          scrollbar-always-on="true"
          border
          v-loading="loading"
          :data="dataSource"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" align="center" :selectable="selectHandle" />
          <el-table-column type="index" label="序号" width="80" />
          <el-table-column prop="clueNumber" label="跟单号" width="180">
            <template #default="scope">
              <div style="color: #409eff; cursor: pointer" @click="handleView(scope.row, scope.$index)">{{ scope.row.clueNumber }}</div>
            </template>
          </el-table-column>
          <el-table-column prop="followDate" label="跟单日期" width="120">
            <template #default="scope">
              {{scope.row.followDate && moment(scope.row.followDate).format('YYYY-MM-DD') || ''}}
            </template>
          </el-table-column>
          <el-table-column prop="clueName" label="项目名称" width="180" />
          <el-table-column prop="estimatedTransactionAmount" label="预计成交金额" width="120" />
          <el-table-column prop="stageCycle" label="周期" width="80" >
            <template #default="{row}">
            {{ calcCycle(row) }} 
            </template>

          </el-table-column>
          <el-table-column prop="estimatedBuyDate" label="预计成交时间" width="220" >
            <template #default="{row}">
              <span v-if="row.estimatedBuyDateStart">{{ moment(row.estimatedBuyDateStart).format('YYYY-MM-DD') }}</span>
              <span v-if="row.estimatedBuyDateEnd">{{ '~' + moment(row.estimatedBuyDateEnd).format('YYYY-MM-DD') }}</span>
              
            </template>

          </el-table-column>
          <el-table-column prop="supplierName" label="客户名称" width="250" />
          <el-table-column prop="sourceName" label="跟单来源" width="160" />
          <el-table-column prop="saleAreaName" label="所属区域" width="100" >
            <template #default="{row}">
              {{ row.saleAreaName  }}
            </template>
          </el-table-column>
          <el-table-column prop="followUserName" label="跟单人" width="120" />
          <el-table-column prop="createByName" label="报备人" width="120" />

          <!-- <el-table-column label="跟单状态" align="left" prop="clueStatus" width="110">
            <template #default="scope">
              <el-tag :type="scope.row.clueStatus == 1 ? 'success' : 'danger'">
                {{ scope.row.clueStatus == 1 ? '已分配' : '未分配' }}
              </el-tag>
            </template>
          </el-table-column> -->
          <el-table-column label="跟单进度" prop="followStageName" fixed="right" width="120">
            <template #default="{ row }">
              <el-tag type="success" v-if="row.followStageName" @click="handleDetail(row)">
                {{ row.followStageName }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="left" width="180" fixed="right">
            <template #default="scope">
              <div style="display: flex; align-items: baseline">
                <a style="color: #409eff" @click="handleRenew(scope.row)">进展</a>
                <el-divider direction="vertical"></el-divider>
                <a style="color: #409eff" @click="handleTranser(scope.row.id)">移交</a>
                <el-dropdown>
                  <span class="el-dropdown-link">
                    更多
                    <el-icon class="el-icon--right">
                      <arrow-down />
                    </el-icon>
                  </span>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <!-- <el-dropdown-item  @click="handleReceive(scope.row)">分配</el-dropdown-item> -->
                      <!-- <el-dropdown-item  @click="handleTranser(scope.row)">移交</el-dropdown-item> -->
                      <el-dropdown-item @click="handleViewHistory(scope.row)">历史</el-dropdown-item>
                      <el-dropdown-item @click="handleEdit(scope.row)">编辑</el-dropdown-item>
                      <el-dropdown-item @click="handleDelete(scope.row.id)">删除</el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="total > 0"
          :total="total"
          v-model:page.sync="queryParams.pageNum"
          v-model:limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-card>
      <div class="fixed-icon" @click="handleEdge" v-show="!showTree">
        <el-icon>
          <DArrowRight />
        </el-icon>
      </div>
    </div>
    <addForm ref="modelForm" :data="dataSource" :index="currentIndex" :classifyList="classifyList" @ok="addOk"></addForm>
    <addFormType ref="addFormType" @ok="listFollowType"> </addFormType>
    <receiveForm ref="receiveForm" :userList="userList" @ok="getList"></receiveForm>
    <transer ref="transer" @ok="getList"></transer>
    <historyForm ref="historyForm"></historyForm>
    <progressForm ref="progressForm" @ok="addOk" ></progressForm>
    <trackingDetail ref="trackingDetail"></trackingDetail>
    <addContractForm ref="addContractForm"></addContractForm>
  </div>
</template>
  
<script>
import addForm from './modules/addForm.vue';
import transer from './modules/transer.vue';
import historyForm from './modules/historyForm.vue';
import addFormType from '@/views/goods/followType/modules/addForm.vue';
import receiveForm from './modules/receiveForm.vue';
import listMixin from '@/mixins/listMixin';
import { provinceAndCityData, pcTextArr, regionData, pcaTextArr, codeToText } from 'element-china-area-data';
import { listFollowType } from '@/api/goods/followType';
import { listByTypeId } from '@/api/goods/followStage';
import request from '@/utils/request';
import moment from 'moment';
import zk from '@/assets/images/zhankai.svg';
import zd from '@/assets/images/zhedie.svg';
import progressForm from '@/views/goods/tracking/components/progressForm.vue';
import trackingDetail from '@/views/goods/clue/modules/trackingDetail.vue';
import addContractForm from '@/views/goods/crmContract/modules/addForm.vue';
export default {
  name: 'customer',
  components: {
    addForm,
    transer,
    receiveForm,
    addFormType,
    historyForm,
    progressForm,
    trackingDetail,
    addContractForm
  },
  mixins: [listMixin],
  data() {
    return {
      queryParams: {
        pageNum: 1,
        pageSize: 10
      },
      urls: {
        list: '/order/clue/list',
        delete: '/order/clue'
      },
      currentIndex: 0,
      price_level: [],
      counting_method: [],
      options: provinceAndCityData,
      selectedOptions: [],
      dateRange: [],
      currentIndex: 0,
      followTypeList: [],
      imgs: [zk, zd],
      tableHeight: 0,
      followTypeList: [],
      showTree: true,
      currentItem: {}
    };
  },
  mounted() {
    this.$nextTick(() => {
      setTimeout(() => {
        this.tableHeight = this.$refs.table.$el.scrollHeight;
      }, 200);
    });
    // 获取分类列表
    this.getClassifyAllList('1');
    this.getDicts(['price_level', 'counting_method']);
    // 获取所有部门
    this.listSysDept();
    // 获取后台用户
    this.listSysUser();
    this.listFollowType();
  },
  methods: {
    moment,codeToText,

    handleDetail(row) {
      this.$refs.trackingDetail.detail(row);
    },
    // 续费
    handleRenew(row) {
      this.$refs.progressForm.edit(row);
    },
    listAfter() {
      this.$nextTick(() => {
        setTimeout(() => {
          this.tableHeight = this.$refs.table.$el.scrollHeight;
        }, 200);
      });
    },
    // 获取跟单类型
    listFollowType() {
      listFollowType({
        pageSize: 9999,
        pageNum: 1,
        typeCategory:1
      })
        .then((res) => {
          let arr = (res.rows || []).map((v) => ((v.children = []), v));
          this.followTypeList = [
            {
              id: '',
              typeName: '全部',
              children: arr
            }
          ];
        })
        .catch((err) => {
          console.log(err);
        });
    },
    handleView(row, index) {
      this.$refs.modelForm.view(row, index, this.dataSource);
    },
    handleViewHistory(row, index) {
      this.$refs.historyForm.view(row);
    },
    codeToText(code) {
      return code
        .split(',')
        .map((item) => {
          return codeToText[item];
        })
        .join('/');
    },
    itemClick(item, index) {
      this.currentItem = item;
      this.queryParams.followTypeId = item.id;
      this.getList();
    },

    handleAddType() {
      this.$refs.modelFormType.add({});
    },
    handleEditType() {
      this.$refs.modelFormType.edit(this.currentItem);
    },
    handleDelType() {
      this.$refs.modelFormType.add({});
    },
    listByTypeId(id) {
      return new Promise((resolve, reject) => {
        listByTypeId(id).then(res => {
          resolve(res)
        })
      })
    },
    getQueryParams() {
      if (this.selectedOptions.length) {
        this.queryParams.country = this.selectedOptions[this.selectedOptions.length - 1];
      } else {
        this.queryParams.country = '';
      }
      let params = Object.assign({}, this.queryParams);
      params.params = { ...this.params };
      if (this.dateRange && this.dateRange.length) {
        params.params['createBeginTime'] = this.dateRange[0] + ' 00:00:00';
        params.params['createEndTime'] = this.dateRange[1] + ' 23:59:59';
      }
      return params;
    },
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10
      };
      this.selectedOptions = [];
      this.dateRange = [];
      this.getList();
    },
    handleReceive(row) {
      this.$refs.receiveForm.edit(row);
    },
    handleTranser(row) {
      console.log('666', 666);
      this.$refs.transer.edit(row);
    },

    handleAddClassify() {
      this.$refs.addFormType.add({typeCategory:1});
    },
    handleEditClassify() {
      console.log(this.currentItem, 'this.currentItem');
      if (!this.currentItem || !this.currentItem.id) {
        this.$message.warning('请选择类型');
        return;
      }
      this.$refs.addFormType.edit(this.currentItem);
    },
    handleDelClassify() {
      if (!this.currentItem) {
        this.$message.warning('请选择类型');
        return;
      }
      this.$modal
        .confirm('确定删除？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        .then(() => {
          console.log('666 :>> ', 666);
          request({
            url: '/order/followType/' + this.currentItem.id,
            method: 'delete'
          }).then((res) => {
            if (res.code == 200) {
              this.$modal.msgSuccess('删除成功');
              this.currentItem = {};
              this.listFollowType();
            } else {
              this.$modal.msgError(res.msg);
            }
          });
        })
        .catch(() => {});
    },
    /**
     * 计算周期
     */
    calcCycle(row) {
      let item = row.jzgFollowStageVoList.find((v) => v.id == row.followStageId);
      if (item) {
        let endDate = item.progressCoefficient == '100%' ? moment(row.orderFollowDate).format('YYYY-MM-DD') : moment().format('YYYY-MM-DD');
        let starDate = moment(row.followDate).format('YYYY-MM-DD');
        return moment(endDate).diff(starDate, 'days') + 1;
      }
      return '';
    },
    // 新增成功回调
    async addOk(form) {
      this.getList();
      // 判断跟单阶段是否到合同，如果是则继续创建合同
      const stage = await this.listByTypeId(form.followTypeId);
      const item = stage.find(v => v.id === form.followStageId);
      if (item && item.stageProcess == '1') {
        
      this.$modal
        .confirm('是否继续创建合同？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        .then(() => {
          this.$refs.addContractForm.link(form);
        })
        .catch(() => {});
      }

    }
  }
};
</script>
  
<style scoped lang="scss">
.tree-item {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  /* border-bottom: 1px solid #777; */
  /* padding: 5px 0; */
  cursor: pointer;
  background-color: #fff;
}

.tree-icon {
  width: 30px;
  height: 30px;
  margin-right: 10px;
}

.item__selected {
  background-color: #e6f7ff;
}

.tree__line {
  width: 24px;
  height: 24px;
  border-bottom: 1px dashed #e5e5eb;
  border-left: 1px dashed #e5e5eb;
}

.tree__title {
  padding: 0 4px;
  margin-bottom: -24px;
}
.left {
  width: 240px;
  border: 1px solid #e6ebf5;
  // position: relative;
  border-radius: 12px;
  overflow-x: hidden;
  overflow-y: auto;
  padding-bottom: 60px;
  background-color: #fff;

  .fodder_list {
    z-index: 20;

    .fodder_item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 10px 20px;
      cursor: pointer;

      .box {
        display: flex;
        justify-content: flex-start;
        align-items: center;

        svg {
          margin-right: 10px;
        }

        .fodder_name {
          font-size: 14px;
          color: #303133;
          width: 84px;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }
      }
    }

    .fodder_item.active,
    .fodder_item:hover {
      background-color: #f5f5f5;
    }
  }

  .buttons {
    display: grid;
    grid-template-columns: 1fr 1fr 1fr;
    position: absolute;
    bottom: 1px;
    width: 238px;
    border-top: 1px solid #e6ebf5;
    background-color: #fff;
    z-index: 21;
    font-size: 12px;
    color: #303133;

    .button {
      cursor: pointer;
      padding: 10px;
      text-align: center;

      i {
        margin-right: 5px;
      }
    }

    .button:not(:last-child) {
      border-right: 1px solid #e6ebf5;
    }

    .button:hover {
      color: #409eff;
    }
  }
}

.left-top {
  display: flex;
  justify-content: space-between;
  padding: 6px 20px;
  border-bottom: 1px solid #e6ebf5;
  align-items: center;

  .box {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    font-size: 24px;
    color: #303133;
    font-weight: bold;
  }
}
.fixed-icon {
  position: fixed;
  //left: 0;
  top: 400px;
  z-index: 999;
  background-color: #409eff;
  padding: 12px 2px;
  color: #fff;
  border-top-left-radius: 4px;
  border-bottom-left-radius: 4px;
  display: flex;
  cursor: pointer;
}

.content {
  display: flex;
  justify-content: space-between;
  position: relative;
}

.w-tree {
  width: calc(100% - 260px);
}

.w-all {
  width: 100%;
}
</style>